import 'dart:convert';
import 'dart:io';

class IOHttpUtils {
  static double width = 0;
  static double height = 0;
  static bool isWeb = false;
  static HttpClient _httpClient = HttpClient();

  static Future<String> getUrl(url) async {
    HttpClientRequest request = await _httpClient.getUrl(Uri.parse(url));
    request.headers.add("Access-Control-Allow-Origin", "*");
    HttpClientResponse response = await request.close();
    if (response.statusCode == HttpStatus.ok) {
      String string = await response.transform(utf8.decoder).join();
      return string;
    } else {
      print("当前网络质量不佳");
      return "";
    }
  }

  static Future<String> postUrl(url, Map<String, String> map) async {
    HttpClientRequest request = await _httpClient.postUrl(Uri.parse(url));
    request.headers.contentType =
        ContentType("application", "x-www-form-urlencoded");
    var keys = map.keys;
    var values = map.values;
    for (var i = 0; i < keys.length; i++) {
      if (i == 0) {
        request.write(keys.elementAt(i) + '=' + values.elementAt(i));
      } else {
        request.write('&' + keys.elementAt(i) + '=' + values.elementAt(i));
      }
    }
    HttpClientResponse response = await request.close();
    if (response.statusCode == HttpStatus.ok) {
      String string = await response.transform(utf8.decoder).join();
      return string;
    } else {
      print("当前网络质量不佳");
      return "";
    }
  }
}
